#include "PathUtil.h"
#include<QDebug>
#include<QDir>
PathUtil::PathUtil()
{

}

QString PathUtil::RelativePathToAbsolutePath(QString ReferencePath,QString RelativePath){
    if(ReferencePath==NULL||ReferencePath.isEmpty()||RelativePath==NULL||RelativePath.isEmpty()){
        qWarning()<<"input parameter can not be null."<<endl;
        return "";
    }
      QString AbsolutePath="";
    if(ReferencePath.endsWith("\\")||ReferencePath.endsWith("/")){
        AbsolutePath = ReferencePath;
    }else{
        AbsolutePath  = ReferencePath+"\\";
    }
  ;
    QString HandlePathStr = RelativePath;
   while(HandlePathStr.startsWith("./")||HandlePathStr.startsWith("../")){
        if(HandlePathStr.startsWith("./")){
            HandlePathStr=HandlePathStr.mid(2);
        }else if(HandlePathStr.startsWith("../")){
            HandlePathStr=HandlePathStr.mid(3);
            if(!QDir(AbsolutePath).cdUp()){
                qWarning()<<"the relative path is not right.AbsolutePath:"<<AbsolutePath<<endl;
                return "";
            }
        }
    }
   AbsolutePath+=HandlePathStr;
   return AbsolutePath;


}

QString PathUtil::getParentPath(QString FilePath){
    if(FilePath==NULL||FilePath.isEmpty()){
        qWarning()<<"File path in PathUtil::getParentPath is null."<<endl;
        return NULL;
    }
    QString handlePath  = FilePath;
    handlePath.replace("\\","/");
    int index = 0;
    if((index=handlePath.lastIndexOf("/"))!=-1){
        handlePath=handlePath.mid(0,index);
    }else{
        return "";
    }
    return handlePath;

}

bool PathUtil::makeDirs(QString FilePath, bool IsFold){
    if(FilePath==NULL||FilePath.isEmpty()){
        qWarning()<<"Input parameter in PathUtil::makeDirs can not be null."<<endl;
        return false;
    }
    QString handlePath= "";
     if(IsFold){
        handlePath = FilePath;
     }else{
        handlePath = PathUtil::getParentPath(FilePath);
     }
        if(QDir(handlePath).exists()){
            return true;
        }else{
            QString patrentPath = PathUtil::getParentPath(handlePath);
            if(!PathUtil::makeDirs(patrentPath,true)){
                qWarning()<<"makeDirs error."<<endl;
                return false;
            }else{
                if(!QDir(handlePath).mkdir(handlePath)){
                    qWarning()<<"makeDirs "<<handlePath<<" error."<<endl;
                    return false;
                }
            }
        }
    return true;
}



















